package com.dsteiner.xelavos.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import com.dsteiner.widgets.client.IJsUtil;
import com.dsteiner.widgets.client.controller.PopupOverlayController;
import com.dsteiner.widgets.client.model.PopupOverlayModel;
import com.dsteiner.xelavos.client.DashletWidget.DashletModel;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;

public class DashletDisplayController {

	private PopupOverlayModel popupOverlayModel;
	private DashletModel dashletModel;
	private IJsUtil jsUtil;

	public void registerPopupOverlayModel(PopupOverlayModel popupOverlayModel) {
		this.popupOverlayModel = popupOverlayModel;
		popupOverlayModel.addPropertyChangeListener("visible", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				dashletModel.setVisible(false);
			}
		});
	}

	public void registerDashletModel(DashletModel dashletModel) {
		this.dashletModel = dashletModel;
		dashletModel.addPropertyChangeListener("visible", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateVisibility();
				updatePosition();
			}
		});
	}
	
	public void registerJsUtil(IJsUtil jsUtil) {
		this.jsUtil = jsUtil;
		jsUtil.addWindowResizeHandler(new ResizeHandler(){
			public void onResize(ResizeEvent event) {
				updatePosition();
			}
		});
	}
	
	private void updatePosition() {
		if(popupOverlayModel.isVisible())
			PopupOverlayController.showAtCenter(popupOverlayModel);
	}

	private void updateVisibility() {
		boolean visible = dashletModel.isVisible();
		if(visible)
			PopupOverlayController.showAtCenter(popupOverlayModel);
		else
			popupOverlayModel.setVisible(false);
	}
	

}
